package util.ui;

import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.File;
import java.io.FileDescriptor;

import util.Debug.ErrorReport;

// mdb added 3/10/08
public class TeeOutputStream extends PrintStream {
	PrintStream oldStream;
	FileDescriptor fd;
	
	public TeeOutputStream(FileOutputStream fos) throws Exception {
		super(fos);
		fd = fos.getFD();
		oldStream = System.err;
	}
	
	public void write(byte[] buf, int off, int len) 
	{
		oldStream.write(buf, off, len);
		super.write(buf, off, len);
		oldStream.flush();
		super.flush();
		try { fd.sync(); } // wait on flush to disk
		catch (Exception e) { }
	}
	
	static public TeeOutputStream createTeeOutputStream(File f)
	{
		TeeOutputStream newOut = null;
    	try
    	{
    		if ( f.exists() )
    			f.delete();
    		newOut = new TeeOutputStream( new FileOutputStream(f) );
    	}
	    catch ( Exception err )
	    {
	    	ErrorReport.reportError(err);
	    }
	    
	    return newOut;
	}
}
